import { sendMessage, getMessageList } from '@/api/message'

import { initWebSocket, getWebsocket } from '@/utils/socket'

import { setCandidate, requestVideo, offer, answer, localSetAnswer, closeRTC } from '@/utils/rtc'

const getDefaultState = () => {
  return {
    onmessage: null,
  }
}

const state = getDefaultState()

const mutations = {
  SET_ONMESSAGE: (state, onmessage) => {
    state.onmessage = onmessage
  },
}

const actions = {
  // 初始化socket
  async initSocket({ state }, onmessage, onerror) {
    return new Promise((resolve, reject) => {
      initWebSocket(onmessage, onerror)
    })
  },

  // 获取socket
  async getWebsocket() {
    return new Promise((resolve, reject) => {
      resolve(getWebsocket())
    })
  },
  // 发送消息
  async sendMessage({ state }, message) {
    return new Promise((resolve, reject) => {
      sendMessage(message)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取消息记录
  async getMessageList({ state }, message) {
    return new Promise((resolve, reject) => {
      getMessageList(message)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 请求视频通话
  async requestVideo({ state }, to) {
    return new Promise((resolve, reject) => {
      requestVideo(to)
    })
  },

  // 发送offer
  async offer({ state }, { localVideo, remoteVideo, to }) {
    return new Promise((resolve, reject) => {
      offer(localVideo, remoteVideo, to)
        .then((offer) => {
          resolve(offer)
        })
        .catch((err) => {
          reject(err)
        })
    })
  },

  // 发送answer
  async answer({ state }, { localVideo, remoteVideo, offer, to }) {
    return new Promise((resolve, reject) => {
      answer(localVideo, remoteVideo, offer, to)
        .then((answer) => {
          resolve(answer)
        })
        .catch((err) => {
          reject(err)
        })
    })
  },

  // 发送candidate
  async candidate({ state }, { candidate }) {
    return new Promise((resolve, reject) => {
      setCandidate(candidate)
        .then(() => {
          resolve()
        })
        .catch((err) => {
          reject(err)
        })
    })
  },

  // 关闭rtc
  async close({ state }, localVideo) {
    return new Promise((resolve, reject) => {
      try {
        resolve(closeRTC(localVideo))
      } catch (err) {
        reject(err)
      }
    })
  },

  async localSetAnswer({ state }, answer) {
    return new Promise((resolve, reject) => {
      localSetAnswer(answer)
        .then(() => {
          resolve()
        })
        .catch((err) => {
          reject(err)
        })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
